<script lang="ts">
import { ref, reactive } from 'vue'
import { Delete, Download, Plus, ZoomIn, UploadFilled, User, SwitchButton } from '@element-plus/icons-vue'

import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules, type UploadFile, } from 'element-plus'

import { createRequirementService } from '@/api/requirement.js'
import router from '@/router'
import { useTokenStore } from '@/stores/token'



const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)


const handleRemove = (file: UploadFile) => {
    console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
    console.log(file)
}

const formSize = ref<ComponentSize>('default')
const requirements = ref({
    title:'',
    budget: '',
    taskType: '',
    contactPerson: '',
    contactInfo: '',
    content: '',
})


const handleCommand = (command) => {
  if (command === 'logout') {
    //退出登录
    ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        try {
          // 清空pinia中的token和个人信息
          const tokenStore = useTokenStore();
          tokenStore.removeToken();

          // 跳转到登录页
          router.push('/login');

          // 更新 localStorage
          localStorage.setItem('isLoggedIn', 'false');
        } catch (error) {
          console.error("发生错误：", error);
          // 可以选择是否在这里显示错误消息或其他处理
        }
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage({
          type: 'info',
          message: '取消退出',
        });
      });
  }
}

const rules = ({
    title: [
        { required: true, message: '请填写任务标题', trigger: 'blur' },
        { min: 3, max: 15, message: '长度至少3到15个字符', trigger: 'blur' },
    ],
    budget: [
        { required: true, message: '请输入预算费用（元）', trigger: 'blur' },
        { min: 1, max: 10, message: '长度至少1个字符，最多10个字符', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的数字，最多两位小数', trigger: 'blur' },
    ],
    taskType: [
        {
            required: true,
            message: '请选择任务类型',
            trigger: 'change',
        },
    ],
    contactPerson: [
        { required: true, message: '请输入姓名或称呼', trigger: 'blur' },
        { min: 2, max: 15, message: '长度必须为2到15位的汉字', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]{2,15}$/, message: '姓名或称呼必须为2到15位汉字', trigger: 'blur' },
    ],
    contactInfo: [
        { required: true, message: '请输入联系电话或微信号', trigger: 'blur' },
        { min: 3, message: '长度至少3个字符', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入任务详细描述', trigger: 'blur' },
    ],
})

// 表单提交
const submitForm = async function () {
  console.log('提交表单开始')

  const ruleForm = this.$refs.ruleFormRef // 通过 $refs 获取表单实例

  if (!ruleForm) {
    console.log('ruleFormRef 未绑定到表单实例')
    return
  }
  ruleForm.validate(async (valid) => {
    console.log('验证完成，验证结果:', valid)
    if (valid) {
      try {
        const result = await createRequirementService(requirements.value)
        ElMessage.success(result.data ? result.data : '提交成功')
        console.log('数据提交成功')
        router.push('/task') // 假设这是提交成功后的跳转函数
        getTasks() // 假设这是重新加载内容的函数
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查填写信息')
      }
    } else {
      console.log('表单验证失败')
      ElMessage.error('表单验证失败，请检查输入内容')
    }
  })
}
const getTasks = () =>{
    console.log('加载任务大厅内容...')
}

export default {
    computed: {
        safeName() {
            return this.yourObject ? this.yourObject.name : '默认值';
        }
    },
    components: {
        Delete,
        Download,
        Plus,
        ZoomIn,
        UploadFilled,
        User,
        SwitchButton,
    },
    data() {
        return {
            activeIndex: '2',
            searchQuery: '',
            isLoggedIn: false,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            isDark: false,
            formSize,
            rules,
            User,
            SwitchButton,
            dialogImageUrl,
            requirements,
            dialogVisible,
            disabled,
            handleSelect: '',
            handlePictureCardPreview,
            handleRemove,
            handleDownload,
            handleCommand,
        }
    },
    methods: {
        navigateTologin(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`); // 跳转到登录页面
        },
        onError(event) {
            event.target.onerror = null; // 避免无限循环
            event.target.src = 'images/default-icon.png'; // 设置默认图标
        },
        setDefaultLogo() {
            this.logoSrc = 'src/assets/logo.jpg';
        },
        setDefaultIcon(event) {
            event.target.src = 'images/default-icon.png';
        },
        setDefaultAvatar(event) {
            event.target.src = 'images/default-avatar.jpg';
        },
        navigateTo(link) {
            window.location.href = link;
        },
        search() {
            console.log('Searching for:', this.searchQuery);
        },
        goToDetails(service) {
            console.log('Going to details for:', service.title);
        },
        submitForm,
    }
}
</script>
<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-105%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton" @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-main style="max-width: 750px;border: 1px solid #ccc;padding: 20px;margin: 20px auto;">
        <h1 style="text-align: center;">发布需求</h1>
        <el-form ref="ruleFormRef" style="max-width: 750px;" :model="requirements" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="任务标题" prop="title">
                <el-input v-model="requirements.title" placeholder="请填写任务标题" />
            </el-form-item>
            <el-form-item label="预算" prop="budget">
                <el-input v-model="requirements.budget" placeholder="请填写任务预算" />
            </el-form-item>
            <el-form-item label="任务类型" prop="taskType">
                <el-select v-model="requirements.taskType" placeholder="请选择任务类型">
                    <el-option label="原型设计" value="原型设计" />
                    <el-option label="前端开发" value="前端开发" />
                    <el-option label="后端开发" value="后端开发" />
                    <el-option label="整套系统开发" value="整套系统开发" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="requirements.contactPerson" placeholder="请填写联系人姓名" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contactInfo">
                <el-input v-model="requirements.contactInfo" placeholder="请填写联系方式" />
            </el-form-item>
            <el-form-item label="任务详细描述" prop="content">
                <el-input v-model="requirements.content" type="textarea" placeholder="请填写任务详细描述" />
            </el-form-item>
            <el-form-item label="可上传附件" prop="file">
                <el-upload class="upload-demo" drag
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple>
                    <el-icon class="el-icon--upload">
                        <UploadFilled />
                    </el-icon>
                    <div class="el-upload__text">
                        可将附件拖拽到此处或<em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            jpg/png文件不能超过500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item style="margin-left: 320px;">
                <el-button type="primary" @click="submitForm">提交</el-button>
            </el-form-item>
        </el-form>
    </el-main>
    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关于我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反馈</a> |
                <text style="color: rgb(78, 77, 77);">@“码上有钱”程序员接单平台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
</template>

<style>
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.footer {
    margin-top: 30px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}
</style>